package ouc.pkere.utils.generator.codegen;

import ouc.pkere.utils.generator.utils.CommonUtils;

import java.io.File;

/**
 * Repository代码生成器
 *
 * @author Wang xiaodong
 * 2018-06-11 16:08
 *
 */
public class RepositoryJavaCodeGenerator {

    private String primaryKeyTypeStr;
    private String packageName;
    private String packagePath;
    private String moduleName;

    public RepositoryJavaCodeGenerator() {
    }

    public RepositoryJavaCodeGenerator(String primaryKeyTypeStr,
                                       String pkgName,
                                       String pkgPath,
                                       String moduleName) {
        super();
        this.primaryKeyTypeStr = primaryKeyTypeStr;
        this.packageName = pkgName;
        this.packagePath = pkgPath;
        this.moduleName = moduleName;
    }

    public void generate() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageName + ".repository;\r\n\r\n");

        sb.append("import org.springframework.data.jpa.repository.JpaRepository;\r\n\r\n");

        // 生成导入本模块Entity的字符串
        sb.append("import " + this.packageName + ".entity." + this.moduleName + "Entity;\r\n\r\n");



        if (primaryKeyTypeStr == null || primaryKeyTypeStr.isEmpty()) {
            primaryKeyTypeStr = "Integer";
        }

        sb.append("public interface " + this.moduleName + "Repository" +
                " extends JpaRepository<" + this.moduleName + "Entity, " + primaryKeyTypeStr + "> { }");


        // Repository的完整生成路径包含repository子目录
        String repositoryFullPath = this.packagePath + File.separator + "repository";

        File repositoryFullPathOp = new File(repositoryFullPath);

        if (!repositoryFullPathOp.exists()) {
            repositoryFullPathOp.mkdir();
        }

        String repositoryJavaFilePathName =repositoryFullPath + File.separator +
                this.moduleName + "Repository" + ".java";

        System.out.println(repositoryJavaFilePathName);

        CommonUtils.codeToSrcFile(repositoryJavaFilePathName, sb.toString());

    }


    public String getPrimaryKeyTypeStr() {
        return primaryKeyTypeStr;
    }

    public void setPrimaryKeyTypeStr(String primaryKeyTypeStr) {
        this.primaryKeyTypeStr = primaryKeyTypeStr;
    }




    public static void main(String[] args) {
        //RepositoryJavaCodeGenerator testGen = new RepositoryJavaCodeGenerator("abc");
    }
}